<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" :model="queryForm">
      <el-form-item label="订单id" prop="orderId">
        <el-input
          v-model="queryForm.orderId"
          size="small"
          placeholder="请输入订单id"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryForm.goodsName"
          size="small"
          placeholder="请输入商品名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买家真实名称" prop="buyUserName">
        <el-input
          v-model="queryForm.buyUserName"
          size="small"
          placeholder="请输入买家真实名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卖家真实名称" prop="saleUserName">
        <el-input
          v-model="queryForm.saleUserName"
          size="small"
          placeholder="请输入卖家真实名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买家id" prop="buyerId">
        <el-input
          v-model="queryForm.buyerId"
          size="small"
          placeholder="请输入买家id"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="卖家id" prop="saleUserId">
        <el-input
          v-model="queryForm.saleUserId"
          size="small"
          placeholder="请输入卖家id"
          @keyup.enter.native="handleQuery"
        />
        
      </el-form-item>
      <el-form-item label="订单状态" prop="saleStatus">
        <el-select
          v-model="selectOptionValue"
          placeholder="订单状态"
          clearable
          size="small"
          @change="handleChange"
          style="width: 120px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item >
        <span>下架状态：</span>

        <el-select
          v-model="selectDown"
          placeholder="下架状态"
          clearable
          size="small"
          @change="handleOpenGranary"
          style="width: 120px"
          pla
        >
          <el-option
            v-for="dict in selectDownOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
            
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item>
        <span>下架：</span>
        <el-switch
            v-model="selectDown"
            @change="handleOpenGranary"
         />

      </el-form-item> -->
      <el-form-item label="上架时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="timestamp"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="loadingDown"
          size="mini"
          @click="handleDownLoad"
        >下载订单</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd()">新增</el-button>
      </el-col>
    </el-row> -->

    <el-table
      v-loading="loading"
      border
      :data="orderList"
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column
        align="center"
        min-width="100"
        label="商品ID"
        prop="id"
        width="50"
      />
      <el-table-column
        align="center"
        min-width="100"
        label="商品名称"
        prop="goodsName"
        sortable="custom"
        width="500"
      />
      <el-table-column align="center" label="商品单价" prop="goodsPrice" width="100" />
      <el-table-column align="center" label="订单用户id" prop="buyUserId" width="100" />
      <el-table-column align="center" label="买方姓名" prop="buyUserName" width="100" />
      <!-- <el-table-column align="center" label="商品数量" prop="goodsCount" width="100" /> -->
      <el-table-column align="center" label="上架时间" prop="groundingTime" width="200" />
      <el-table-column align="center" label="下架时间" prop="downTime" width="200" v-show="queryForm.type == 3" />

      <el-table-column align="center" label="卖方id" prop="saleUserId" width="100" />
      <el-table-column align="center" label="卖方姓名" prop="saleUserName" width="100" />
      <el-table-column align="center" label="订单状态" width="100">
        <template slot-scope="scope">
          <el-tag>{{ getStauts(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="支付类型">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.saleStatus | paymentStatusEnumFilter }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" width="150">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            @click="handleOrder(scope.row)"
          >拆单</el-button>-->
          <el-button 
            v-if="scope.row.type != 3"
            size="mini"
            @click="handleCancelOrder(scope.row)"
          >下架</el-button>
          <el-button
            v-if="scope.row.type == 3"
            size="mini"
            @click="handleUpOrder(scope.row)"
          >上架</el-button>
          <!-- <el-button
            size="mini"
            style="margin-top: 8px;"
            @click="handleCancelOrder(scope.row)"
          >退回订单</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    />

    <!-- <el-dialog :visible.sync="showOrderVisible" title="拆单">

        <el-form ref="formRefs" :model="selectGoods">
          <el-form-item label="商品选择">
            <el-select v-model="formModel.goodsName" @change="changeGoods()" filterable placeholder="请选择">
              <el-option
                v-for="item in goodsOptions"
                :key="item.goodsName"
                :label="item.goodsName"
                :value="item.goodsName"
              />
            </el-select>
        </el-form-item>
        <el-form-item prop="goodsName" label="商品名称" >
          <el-input v-model="formModel.goodsName" placeholder="请选择" disabled/>
        </el-form-item>
        <el-form-item prop="goodsMarketPrice" label="市场价" >
          <el-input v-model="formModel.goodsMarketPrice" placeholder="请选择" disabled/>
        </el-form-item>
        <el-form-item prop="goodsMarketPrice" label="商品图片" >
          <el-image :src="formModel.goodsImg" >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-form-item>
        <el-form ref="formRef" :model="formModel">
        <el-form-item prop="splitCount" label="分配金额" :rules="[{ required: true, message: '请输入分配金额' }]">
          <el-input v-model="formModel.splitCount" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <el-form-item label="买家选择框">
          <el-select v-model="formModel.buyerId" @change="changePeople" filterable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.id + '-' + item.userRealName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="showOrderVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
import {
  purchaseListOrder,
  delOrder,
  listChannel, splitOrderReq, listUser, updateSaleStatus,exporCgOrderListtData,ListGoodsOptions,downCgOrder,upCgOrder,getAdjustmentSwitch
} from '@/api/shop/order'
import { yuan } from '@/utils'
import {excelNameDate} from  '@/utils/index'


const payStatusMap = {
  1: '微信',
  2: '支付宝',
  3: '测试'
}

const orderStatusEnum = {
  1: '已上架',
  2: '已加入购物车',
  3: '已支付待上架'
  // 4: '已上架订单'
}

// const paymentStatusEnum = {
//   0: '已加购', 1: '已确认', 2: '待付款审核', 3: '付款审核通过', 4: '待上架审核', 5: '上架审核通过'
// }

export default {
  name: 'PurchaseOrderList',
  filters: {
    yuan
    // paymentStatusEnumFilter(status) {
    //   if (status === null) {
    //     return '未被购买'
    //   }
    //   return paymentStatusEnum[status]
    // }
  },
  data() {
    return {
      selectDown:0,
      selectDownOptions:[
      {
          value:'上架',
          key:0
        },
        {
          value:'下架',
          key:1
        },
      ],
      loading: true,
      loadingDown:false,
      // 列表总数
      total: 0,
      // 日期范围
      dateRange: [],
      // 订单状态数据字典
      orderStatusOptions: [],
      selectOptionValue:'',
      statusOptions:[
      {
          value:'已加入购物车',
          key:1
        },
        {
          value:'已支付待上架',
          key:2
        },
        {
          value:'已上架',
          key:3
        },
        {
          value:'已下架',
          key:4
        },
      ],
      payTypeOptions: [
        { name: '微信', value: '1' },
        { name: '支付宝', value: '2' },
        { name: '测试', value: '3' }
      ],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        orderSn: undefined,
        userId: undefined,
        name: undefined,
        buyUserName:undefined,
        saleUserName:undefined,
        type:undefined
        // status: undefined,
        // saleStatus: undefined
      },
      // 角色列表
      orderList: [],
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: []
      },
      channels: [],
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipFormRules: {
        shipChannel: [
          { required: true, message: '发货渠道不能为空', trigger: 'blur' }
        ],
        shipSn: [
          { required: true, message: '发货编号不能为空', trigger: 'blur' }
        ]
      },
      shipDialogVisible: false,
      showOrderVisible: false,
      formModel: {
        tableData: []
      },
      options: [],
      goodsOptions:[],
      selectGoods:{}
    }
  },
  created() {
    this.getOptions()
    // this.getGoodsOptions()

    this.getList()
    this.getChannel()
    this.getDicts('orderStatus').then((response) => {
      const {
        map: { data }
      } = response
      this.orderStatusOptions = data
    })
  },
  methods: {
    changeGoods(val){
      console.log(val)
      this.goodsOptions.forEach(item=>{
        if(item.goodsName === this.formModel.goodsName){
          this.$set(this.formModel,'goodsImg',item.goodsImg)
          this.$set(this.formModel,'goodsMarketPrice',item.goodsMarketPrice)
        }
      })

    },
    handleChange(val){
      // if (row.status == 1) {
      //   return '已上架'
      // } else {
      //   if (row.saleStatus == 1 || row.saleStatus == 0 || row.saleStatus == null) {
      //     return '已加入购物车'
      //   } else if (row.saleStatus == 3) {
      //     return '已支付待上架'
      //   }
      // }
      console.log(val)
      if(val == 3){
        this.$set(this.queryForm,'status',1)
        this.$set(this.queryForm,'saleStatus',undefined)
        this.$set(this.queryForm,'type',undefined)

      }else if(val == 2){
        this.$set(this.queryForm,'status',2)
        this.$set(this.queryForm,'saleStatus',"3")
        this.$set(this.queryForm,'type',undefined)


      }else if(val ==4){
        this.$set(this.queryForm,'status',undefined)
        this.$set(this.queryForm,'saleStatus',undefined)
        this.$set(this.queryForm,'type',3)
      }else {
        this.$set(this.queryForm,'status',2)
        this.$set(this.queryForm,'saleStatus',"1,0,null")
        this.$set(this.queryForm,'type',undefined)

      }
      console.log(this.queryForm)
      console.log(val)
    },
    changePeople(){
      this.options.forEach(item=>{
        if(item.id == this.formModel.buyerId){
          this.$set(this.formModel,'')
        }
      })
    },
    // 获取买家
    async getOptions() {
      const {
        map: { userList }
      } = await listUser()
      this.options = userList
    },
    async getGoodsOptions(){
      const {
        map: { changeOrder }
      } = await ListGoodsOptions()
      this.goodsOptions =changeOrder
      console.log(res)
    },

    // async onConfirm() {
    //   this.$refs.formRef.validate(async valid => {
    //     if (!valid) {
    //       return
    //     }
    //     await splitOrderReq({ ...this.formModel })
    //     this.$message.success('操作成功')
    //     this.formModel = {}
    //     this.$refs.formRef.resetFields()
    //     this.getList()
    //     this.showOrderVisible = false
    //   })
    // },
    // async handleOrder(record) {
    //   let status =this.getStauts(record)
    //   if(status == '已支付待上架' ){
    //     return this.$message.error('当前订单状态已支付未上架，无法拆单')
    //   }

    //   this.formModel.orderId = record.id     
    //   this.showOrderVisible = true
    // },
    handleStatus(record) {
      updateSaleStatus({ 'orderId': record.id }).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
        this.getList()
      })
    },
    getChannel() {
      listChannel().then((response) => {
        this.channels = response.map.data
      })
    },
    handleQuery() {
      if(this.queryForm.saleUserName == ''){
        this.$set(this.queryForm,'saleUserName',undefined)
      }
      if(this.queryForm.buyUserName == ''){
        this.$set(this.queryForm,'buyUserName',undefined)
      }
      this.getList()
    },
    /**
     * 表单重置
     */
    resetQuery() {
      this.selectOptionValue=""
      this.$set(this.queryForm,'status',undefined)
        this.$set(this.queryForm,'saleStatus',undefined)
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.handleQuery()
    },
    async getList() {
      const {
        map: {
          page: { records: data, total }
        }
      } = await purchaseListOrder({ ...this.queryForm, timeStr: this.dateRange && this.dateRange.length ? `${this.dateRange[0]},${this.dateRange[1]}` : '' })
      console.log(this.queryForm)
      this.total = total
      this.orderList = data
      this.loading = false
    },
    /**
     * 后端排序
     */
    handleSortChange(sort) {
      console.log(sort)
      this.queryForm.sortName = sort.prop
      this.queryForm.sortOrder = sort.order
      this.getList()
    },
    /**
     * 删除按钮
     */
    async handleDelete(row) {
      const orderId = row.id
      this.$confirm(
        '是否确认删除订单编号为 [' + row.orderSn + '] 的订单吗?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delOrder(orderId)
        })
        .then(() => {
          this.getList()
          this.$message.success('删除成功')
        })
        .catch(function(e) {})
    },
    getStauts(row) {
      if(row.type == 3){
        return '已下架'

      }
      if (row.status == 1) {
        return '已上架'
      } else {
        if (row.saleStatus == 1 || row.saleStatus == 0 || row.saleStatus == null) {
          return '已加入购物车'
        } else if (row.saleStatus == 3) {
          return '已支付待上架'
        }
      }
    },
    handleDownLoad() {
      this.$confirm(
        '是否下载今日采购数据',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
        .then(res => {
          exporCgOrderListtData().then(res => {
            const blob = new Blob([res.data], { type: 'application/msword' })// new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
            console.log(blob)
            const dates = excelNameDate()
            
            // const fileName = `${month}-${day} ${h}:${m}:${s}调单数据.xls`// 下载文件名称
            const fileName = `采购订单数据${dates}.xls`// 下载文件名称
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
          })
          // this.loadingDown = true
          console.log(res)
        })
    },
    // 下架操作
    async handleCancelOrder(row) {
      console.log(row)
      // debugger
      // const data = await getAdjustmentSwitch()
      // if(data.map.is_adjust == 1){
      //   return this.$message.error('当前订单已完成调单请于明日已完成调单前下架')
      // }
      downCgOrder({orderId : row.id,downOrUp:0}).then( async res=>{
        if(res.code === 200){
          this.$message.success('下架成功')
        }else{
          this.$message.error(res.message)
        }
        this.loading = true
        await this.getList()
      })
    },
    // 上架架操作
    async handleUpOrder(row) {
      console.log(row)
      downCgOrder({orderId : row.id,downOrUp:1}).then(res=>{
        if(res.code === 200){
          this.$message.success('上架成功')
        }else{
          this.$message.error(res.message)
        }
        this.getList()
      })
    },
    handleOpenGranary(val){
      if(val){
        this.queryForm.type = 3
      }else{
        this.queryForm.type = undefined
      }
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.more_btn{
  margin-left: 10px;
}
.el-image{
  width: 100px;
  height: 100px;
}
.el-icon-picture-outline::before{
  width: 100px;
  height: 100px;
  font-size: 100px;
}
</style>
